//文件访问域名
var ossDomain = "https://pp-friend2.oss-cn-shenzhen.aliyuncs.com";
var globalHeight = '1050';

$(document).ready(function () {
    var envir = 'dev';
    var configMap = {
        dev: {
            //sts授权路径
            apiUrl: "http://test.api.pp.cyhytec.com/pp-api/",
            apiKey: 'gkVy0ddhqllQyNSP5jcZlBJQ2eqke2KD',
            aesKey: 'QrQnatopL0YupvypkOcpZpFd4yZNkEPP',
        },
        prod: {
            apiUrl: "http://test.api.pp.cyhytec.com/pp-api/",
            apiKey: 'B23gepGe6GicSfqHkza5yKBGQz4nXt9X',
            aesKey: 'gtsV4vOXWOBxVlEdPSRF07BaGMUSr6Yx',
        }
    }
    window.CONFIG = configMap[envir];

    var pathname = location.pathname;
    if (window != top && pathname.endsWith("login")) {
        top.location.href = location.href;
    }
});

/**
 * 获取数组对象中指定字段数组
 * @param arr
 * @param id
 * @returns {string}
 */
function getIds(arr, id) {
    var ids = [];
    arr.forEach(function (value) {
        ids.push(value[id]);
    });
    return ids;
}

/**
 * 封装post请求
 * @param url   请求路径（必填）
 * @param data  请求参数（非必填）
 * @param async 请求方式（非必填）
 * @param successFn 请求成功执行方法（非必填）
 * @param errorFn   请求失败执行方法（非必填）
 */
function post(url, data, async, successFn, errorFn){
    $.ajax({
        url: url,
        data: data ? data : {},
        async: async ? async : true,
        dataType: 'json',
        success: function (result) {
            if(result.code == 0){
                if(successFn){
                    successFn(result.data);
                }
            }else{
                if (errorFn) {
                    errorFn();
                }
                layer.msg(result.msg);
            }
            layer.close(layerLoad());
        },
        error: function () {
            layer.msg("请求失败");
        }
    });
}

/**
 * 生成UUID唯一标识
 * @returns {string}
 */
function getUUID() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 32; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    var uuid = s.join("");
    return uuid;
}

/**
 * 生成上传文件名
 * @returns {string}
 */
function getFileName() {
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth();
    var day = date.getDay();
    var time = add0(date.getHours())+date.getHours()+add0(date.getMinutes())+date.getMinutes()+add0(date.getSeconds())+date.getSeconds();
    var fileName = getUUID();
    return year+"/"+add0(month)+month+"/"+add0(day)+day+"/"+time+"/"+fileName;
}
function add0(m){
    return m<10?'0'+m : m;
}

/**
 * 图片放大
 */
$(document).on('mouseover', '.layui-table-cell img', function () {
    layer.photos({
        photos: $(this).parent(),
        anim: 5,
        shade: 0.3
    });
});

/**
 * 视频放大
 */
$(document).on('click', '.layui-table-cell video', function () {
    var src = $(this).attr('src');
    layer.open({
        title: false,
        type: 1,
        offset: '10%',
        area: ['350px', '600px'],
        shadeClose: true,
        content: '<div style="padding: 25px;"><video width="300px" src="'+src+'" controls></div>'
    });
});

/**
 * 获取请求路径中的参数
 * @param variable
 * @returns {*}
 */
function getQueryVariable(variable){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if(pair[0] == variable){return pair[1];}
    }
    return(false);
}

/**
 * sha1加密
 * @param s
 * @returns {string}
 */
function sha1(s) {
    var data = new Uint8Array(encodeUTF8(s))
    var i, j, t;
    var l = ((data.length + 8) >>> 6 << 4) + 16, s = new Uint8Array(l << 2);
    s.set(new Uint8Array(data.buffer)), s = new Uint32Array(s.buffer);
    for (t = new DataView(s.buffer), i = 0; i < l; i++)s[i] = t.getUint32(i << 2);
    s[data.length >> 2] |= 0x80 << (24 - (data.length & 3) * 8);
    s[l - 1] = data.length << 3;
    var w = [], f = [
            function () { return m[1] & m[2] | ~m[1] & m[3]; },
            function () { return m[1] ^ m[2] ^ m[3]; },
            function () { return m[1] & m[2] | m[1] & m[3] | m[2] & m[3]; },
            function () { return m[1] ^ m[2] ^ m[3]; }
        ], rol = function (n, c) { return n << c | n >>> (32 - c); },
        k = [1518500249, 1859775393, -1894007588, -899497514],
        m = [1732584193, -271733879, null, null, -1009589776];
    m[2] = ~m[0], m[3] = ~m[1];
    for (i = 0; i < s.length; i += 16) {
        var o = m.slice(0);
        for (j = 0; j < 80; j++)
            w[j] = j < 16 ? s[i + j] : rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1),
                t = rol(m[0], 5) + f[j / 20 | 0]() + m[4] + w[j] + k[j / 20 | 0] | 0,
                m[1] = rol(m[1], 30), m.pop(), m.unshift(t);
        for (j = 0; j < 5; j++)m[j] = m[j] + o[j] | 0;
    };
    t = new DataView(new Uint32Array(m).buffer);
    for (var i = 0; i < 5; i++)m[i] = t.getUint32(i << 2);

    var hex = Array.prototype.map.call(new Uint8Array(new Uint32Array(m).buffer), function (e) {
        return (e < 16 ? "0" : "") + e.toString(16);
    }).join("");
    return hex;
}

function encodeUTF8(s) {
    var i, r = [], c, x;
    for (i = 0; i < s.length; i++)
        if ((c = s.charCodeAt(i)) < 0x80) r.push(c);
        else if (c < 0x800) r.push(0xC0 + (c >> 6 & 0x1F), 0x80 + (c & 0x3F));
        else {
            if ((x = c ^ 0xD800) >> 10 == 0) //对四字节UTF-16转换为Unicode
                c = (x << 10) + (s.charCodeAt(++i) ^ 0xDC00) + 0x10000,
                    r.push(0xF0 + (c >> 18 & 0x7), 0x80 + (c >> 12 & 0x3F));
            else r.push(0xE0 + (c >> 12 & 0xF));
            r.push(0x80 + (c >> 6 & 0x3F), 0x80 + (c & 0x3F));
        };
    return r;
}

/**
 * 加载层
 */
function layerLoad(){
    var load = layer.load(2, {
        shade: [0.3, 'gray'],
        content: '操作中...',
        success: function (layero) {
            layero.find('.layui-layer-content').css({
                'padding-top': '39px',
                'width': '60px',
                'textAlign': 'center',
                'backgroundPositionX': 'center'
            });
        }
    });
    return load;
}

/**
 * 获取当前日期回填时间控件
 */
function getNowDate() {
    var date = new Date();
    var y = date.getFullYear();
    var m = date.getMonth()+1;
    var d = date.getDate();
    date = y + '-' + add0(m) + '-' + add0(d);
    return date + ' - ' + date;
}

/**
 * 获取列表当前页码、页数和排序字段
 */
function getCommonData(){
    var page = $(".layui-laypage-skip .layui-input").val();
    //获取当前页条数
    var limit = $(".layui-laypage-limits").find("option:selected").val();
    var field = $('[lay-sort]').parent().parent().attr('data-field');
    var type = $('[lay-sort]').attr('lay-sort');
    var commonData = {'page': page, 'limit': limit, 'field': field, 'type': type};

    return commonData;
}